/**
 * 用户服务
 * 处理用户管理相关业务逻辑
 */

import { request } from '@/utils/request'
import { API_ENDPOINTS } from '@/constants'
import type { User, UserQuery, UserForm } from '@/types/user'
import type { PageResponse } from '@/types/api'

export class UserService {
  /**
   * 获取用户列表
   */
  static async getUserList(params: UserQuery): Promise<PageResponse<User>> {
    try {
      const response = await request.get<PageResponse<User>>(API_ENDPOINTS.USERS, { params })
      return response
    } catch (error) {
      console.error('获取用户列表失败:', error)
      throw error
    }
  }

  /**
   * 获取用户详情
   */
  static async getUserDetail(id: string): Promise<User> {
    try {
      const response = await request.get<User>(API_ENDPOINTS.USER_DETAIL(id))
      return response
    } catch (error) {
      console.error('获取用户详情失败:', error)
      throw error
    }
  }

  /**
   * 创建用户
   */
  static async createUser(userForm: UserForm): Promise<User> {
    try {
      const response = await request.post<User>(API_ENDPOINTS.USERS, userForm)
      return response
    } catch (error) {
      console.error('创建用户失败:', error)
      throw error
    }
  }

  /**
   * 更新用户
   */
  static async updateUser(id: string, userForm: UserForm): Promise<User> {
    try {
      const response = await request.put<User>(API_ENDPOINTS.USER_DETAIL(id), userForm)
      return response
    } catch (error) {
      console.error('更新用户失败:', error)
      throw error
    }
  }

  /**
   * 删除用户
   */
  static async deleteUser(id: string): Promise<void> {
    try {
      await request.delete(API_ENDPOINTS.USER_DETAIL(id))
    } catch (error) {
      console.error('删除用户失败:', error)
      throw error
    }
  }

  /**
   * 批量删除用户
   */
  static async batchDeleteUsers(ids: string[]): Promise<void> {
    try {
      await request.delete(API_ENDPOINTS.USERS, { data: { ids } })
    } catch (error) {
      console.error('批量删除用户失败:', error)
      throw error
    }
  }

  /**
   * 重置用户密码
   */
  static async resetPassword(id: string, newPassword: string): Promise<void> {
    try {
      await request.patch(`${API_ENDPOINTS.USER_DETAIL(id)}/password`, {
        password: newPassword
      })
    } catch (error) {
      console.error('重置密码失败:', error)
      throw error
    }
  }

  /**
   * 更新用户状态
   */
  static async updateUserStatus(id: string, status: number): Promise<void> {
    try {
      await request.patch(`${API_ENDPOINTS.USER_DETAIL(id)}/status`, {
        status
      })
    } catch (error) {
      console.error('更新用户状态失败:', error)
      throw error
    }
  }

  /**
   * 分配用户角色
   */
  static async assignRoles(id: string, roleIds: string[]): Promise<void> {
    try {
      await request.patch(`${API_ENDPOINTS.USER_DETAIL(id)}/roles`, {
        roleIds
      })
    } catch (error) {
      console.error('分配角色失败:', error)
      throw error
    }
  }
}
